<?php
require_once("../../Config.php");
require_once("../../Class/ClassFunc.php");
require_once("../../Class/ClassMysql.php");
require_once("../../Class/ClassCheck.php");
require_once("../../Class/ClassResult.php");

//json头
header("Content-type: application/json");

session_start();
if(!isset($_SESSION["name"])) {
    exit(Result::jsonReturn(1, "未登录"));
}

$uid = $_SESSION["id"];
$uname = $_SESSION["name"];
$uemail = $_SESSION["email"];
$upower = $_SESSION["power"];

if((int)$upower == 0) {
    exit(Result::jsonReturn(1, "权限不足"));
}

$name = $email = "";
$password = Func::encipher(PASSWORD);
$power = 0;

// 校验是否为空
if(Check::isEmpty($_POST["name"])) {
    exit(Result::jsonReturn(1, "名称不得为空"));
}
if(Check::isEmpty($_POST["email"])) {
    exit(Result::jsonReturn(1, "邮箱不得为空"));
}

// 校验是否符合格式
if(Check::isName($_POST["name"])) {
    $name = $_POST["name"];
}else {
    exit(Result::jsonReturn(1, "用户名格式有误"));
}
if(Check::isEmail($_POST["email"])) {
    $email = $_POST["email"];
}else {
    exit(Result::jsonReturn(1, "邮箱格式有误"));
}
if((int)$_POST["power"] == 0 || (int)$_POST["power"] == 1) {
    $power = (int)$_POST["power"];
}else {
    exit(Result::jsonReturn(1, "权限只能选择0或1"));
}
if(isset($_POST["password"])) {
    if(!Check::isEmpty($_POST["password"])) {
        if(Check::isPassword($_POST["password"])) {
            $password = Func::encipher($_POST["password"]);
        }else {
            exit(Result::jsonReturn(1, "密码格式错误"));
        }
    }
}


$db = new DB();
$sql_rows = "SELECT id from qilian_users WHERE name='{$name}'";
if($db->getRows($sql_rows) != 0) {
    exit(Result::jsonReturn(1, "已存在该用户"));
}

$sql = "INSERT INTO qilian_users(name, email, password, power) VALUES('{$name}', '{$email}', '{$password}', {$power})";
$id = 0;
if($id=$db->insert($sql)) {
    exit(Result::jsonReturn(0, "添加用户成功", array(
        "id" => $id,
        "name" => $name,
        "email" => $email,
        "power" => $power)));
}else {
    exit(Result::jsonReturn(1, "添加用户失败"));
}


?>